08. Unit Test Lifecycle
Unit Test Lifecycle
ND079 JPND C3 L4 A08 Unit Test Lifecycles V2
JUnit Lifecycle Stages
If your tests all share similar repeated steps, such as constructing an object or populating certain test data, it can be useful to perform those steps outside the individual unit tests. JUnit takes the following steps for each test class:
- Construct the class
- Run any methods annotated with
@BeforeAll
- For each test:
- Run any methods annotated with
@BeforeEach
- Run the test method
- Run any methods annotated with
@AfterEach
- Run any methods annotated with
- Run any methods annotated with
@AfterAll
You can use the above annotations to identify methods that should run during the testing process. For example, I could modify my AppTest to construct a new App instance for each unit test. This helps make the unit tests even shorter and focus on the specific behavior they're trying to test.
public class AppTest {
//Object under test
private App app;
@BeforeEach
void init() {
this.app = new App();
}
@ParameterizedTest(name = "[{index}] {0} + {1} = {2}")
@DisplayName("Add 6 to normal numbers \uD83D\uDE3B")
@CsvSource({
"6, 5, 11",
"6, 1, 7",
"6, 100, 106",
"6, 1000, 1006",
"6, 100000, 100006"
})
public void addTwoNumbersSlimmer_addSix_returnsNumberPlusSix(int input1, int input2, int expected) {
Assertions.assertEquals(expected, app.addTwoNumbers(input1, input2));
}
}